package com.qdsg.modulesihealsdk.detectStrategy.strategy.gluStrategy;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.example.moduleutils.LogUtil;
import com.ghalife.gha_ble.Bean.W_GluResult;
import com.ghalife.gha_ble.W_GlumeterEvent;
import com.ghalife.gha_ble.W_GlumeterEventType;
import com.ghalife.gha_ble.W_GlumeterListener;
import com.qdsg.modulesihealsdk.detectStrategy.control.DetectBusiness;
import com.qdsg.modulesihealsdk.detectStrategy.control.StrategyCallback;
import com.qdsg.modulesihealsdk.entity.GluResultEntity;
import com.qdsg.modulesihealsdk.utils.SihealUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import cn.com.heaton.blelibrary.packaging.bean.BleRssiDevice;
import cn.com.heaton.blelibrary.packaging.ctrl.GlumeterEvent;
import cn.com.heaton.blelibrary.packaging.ctrl.GlumeterEventType;
import cn.com.heaton.blelibrary.packaging.update.bluetooth.ProgressBean;

import static com.qdsg.modulesihealsdk.utils.SihealSdkConstant.GLU_STATE_2;
import static com.qdsg.modulesihealsdk.utils.SihealSdkConstant.GLU_STATE_3;
import static com.qdsg.modulesihealsdk.utils.SihealSdkConstant.GLU_STATE_4;
import static com.qdsg.modulesihealsdk.utils.SihealSdkConstant.GLU_STATE_5;

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2023/1/31 17:30
 */
public class GluStrategy implements DetectBusiness {
    private W_S_GlumeterWorker glumeterWorker;
    private String userId = "1234";
    private Context context;
    private GluCallback gluCallback;
    private String dinnerTime;
    private String userName;
    private String birthday;
    private String gender;
    private String height;
    private String weight;
    private String diabetes;
    private String fpg;

    @Override
    public void dealDetect(Context context, StrategyCallback strategyCallback) {
        this.context = context;
        if (strategyCallback instanceof GluCallback) {
            this.gluCallback = (GluCallback) strategyCallback;
            gluCallback.detectProgress(0);
            initData();
        }
    }

    public GluStrategy initData(
            String dinnerTime,
            String userName,
            String birthday,
            String userGender,
            String height,
            String weight,
            String diabetes,
            String fpg) {
        this.dinnerTime = dinnerTime;
        this.userName = userName;
        this.birthday = birthday;
        this.gender = userGender;
        this.height = height;
        this.weight = weight;
        this.diabetes = diabetes;
        this.fpg = fpg;
        LogUtil.logAndWrite("__glu-initData",
                "dinnerTime = "+dinnerTime+"\n"+
                "userName = "+userName+"\n"+
                "birthday = "+birthday+"\n"+
                "userGender = "+userGender+"\n"+
                "height = "+height+"\n"+
                "weight = "+weight+"\n"+
                "diabetes = "+diabetes+"\n"+
                "fpg = "+fpg+"\n"
                );
        return this;
    }

    @Override
    public void stopThread() {
        try {
            if (glumeterWorker != null) {
                glumeterWorker.disConn();
                glumeterWorker.stopScan();
                glumeterWorker.stop();
                glumeterWorker = null;
            }

        } catch (Exception e) {

        }
        if (gluCallback != null) {
            gluCallback = null;
        }
    }

    private void initData() {
        glumeterWorker = new W_S_GlumeterWorker(context, listener);
        scan();
//        try {
//            Map<String, Object> map = getMap();
//            if (map != null && glumeterWorker != null) {
//                try {
//                    glumeterWorker.createUser(map);
//                } catch (Exception e) {
//                    if (gluCallback != null) {
//                        gluCallback.occurError("e1:"+e.getMessage());
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    private void scan() {

        if (!checkEmpty("mealtime", dinnerTime)) {
            return;
        }

        Map<String, Object> map = getMap();
        if (map == null) {
            return;
        }
        map.put("userId", userId);
        map.put("mealtime", dinnerTime);
        LogUtil.logAndWrite("__glu-initData-1","userId = "+userId+" mealtime = "+dinnerTime);
        try {
            if (glumeterWorker != null) {
                glumeterWorker.configure(map);
                glumeterWorker.initN_GlumeterWorker(1);
                glumeterWorker.scan();
            }
        } catch (Exception e) {
            if (gluCallback != null) {
                gluCallback.occurError("e2:"+e.getMessage());
            }
        }
    }

    private Map getMap() {
        Map<String, Object> map = new HashMap<String, Object>();
        if (!checkEmpty("userName", userName)) {
            if (gluCallback != null) {
                gluCallback.occurError("userName null");
            }
            return null;
        }
        if (!checkEmpty("birthday", birthday)) {
            if (gluCallback != null) {
                gluCallback.occurError("birthday null");
            }
            return null;
        }
        if (!checkEmpty("gender", gender)) {
            if (gluCallback != null) {
                gluCallback.occurError("gender null");
            }
            return null;
        }
        if (!checkEmpty("height", height)) {
            if (gluCallback != null) {
                gluCallback.occurError("height null");
            }
            return null;
        }
        if (!checkEmpty("weight", weight)) {
            if (gluCallback != null) {
                gluCallback.occurError("weight null");
            }
            return null;
        }
        if (!checkEmpty("diabetes", diabetes)) {
            if (gluCallback != null) {
                gluCallback.occurError("diabetes null");
            }
            return null;
        }
        if (!checkEmpty("fpg", fpg)) {
            if (gluCallback != null) {
                gluCallback.occurError("fpg null");
            }
            return null;
        }
        map.put("userName", userName);
        map.put("birthday", birthday);
        map.put("gender", SihealUtil.transGenderToString(gender)); //男1 女2
        map.put("height", height);
        map.put("weight", weight);
        map.put("diabetes", diabetes);//0正常 2 糖尿病
        map.put("fpg", fpg);//空腹血糖
        return map;
    }

    private boolean checkEmpty(String contentName, String content) {
        if (TextUtils.isEmpty(content) && gluCallback != null) {
            gluCallback.occurError(contentName + "为空");
            return false;
        }
        return true;
    }

    public MHandler mHandler = new MHandler();

    private class MHandler extends Handler {
        public MHandler() {
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg == null) {
                return;
            }
            if (msg.what == 60) {
                W_GlumeterEvent event = (W_GlumeterEvent) msg.obj;
                if (event.getType() == W_GlumeterEventType.NETERROR) {
                    if (gluCallback != null) {
                        gluCallback.deviceState(event.getType().getName() + event.getContent());
                    }

                }
                if (event.getType() == W_GlumeterEventType.CREATEUSERINFOSUCCESS) {
                    //获取用户ID 成功
                    userId = (String) event.getContent();
                    if (gluCallback != null) {
                        gluCallback.deviceState("返回的用户id:" + event.getContent());
                    }

                    // 创建用户信息成功，开始扫描设备
                    scan();


                }
                if (event.getType() == W_GlumeterEventType.UPDATEUSERINFOSUCCESS) {
                    //修改用户信息成功
                    if (gluCallback != null) {
                        gluCallback.deviceState("修改用户信息成功");
                    }


                }

            } else if (msg.what == 61) {
                GlumeterEvent event = (GlumeterEvent) msg.obj;

                if (event.getType() == GlumeterEventType.PRC_DEVICES) {
                    ArrayList<BleRssiDevice> data = (ArrayList<BleRssiDevice>) event.getContent();
                    for (int i = 0; i < data.size(); i++) {
                        String bleName = data.get(i).getDevice().getBleName();
                        if (bleName.startsWith("Glucometer_") || bleName.startsWith("Gluco_")) {
                            conn(data.get(i));
                        }
//                        if (bleName.equals("Glucometer_Y3Ew") || bleName.equals("Glucometer_7lws") || bleName.equals("Glucometer_wIRe")) {
//                            conn(data.get(i));
//                        }
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_NDEV) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("设备不存在没有搜索到设备");
                    }
                    scan();
                }
                if (event.getType() == GlumeterEventType.CONNECTED) {
                    if (gluCallback != null) {
                        //设备准备中，请勿放入手指
                        gluCallback.deviceState(GLU_STATE_2);
                        gluCallback.deviceState("已连接");
                    }
                }
                if (event.getType() == GlumeterEventType.CONNECTTING) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("正在连接");
                    }
                }
                if (event.getType() == GlumeterEventType.DISCONNECTED) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("未连接");
                    }
                }
                if (event.getType() == GlumeterEventType.PRC_INITTIME) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("同步时间完成");

                        //开始检测
                        if (glumeterWorker != null) {
                            glumeterWorker.start();
                        }
                    }

                }
                if (event.getType() == GlumeterEventType.ERR) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("测试失败");
                    }
                }
                if (event.getType() == GlumeterEventType.PRC_INIT) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("初始化进程");
                    }
                }
                if (event.getType() == GlumeterEventType.PRC_READY) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("设备准备完成");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_USER) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("设备没有该用户信息");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_FINGER) {
                    if (gluCallback != null) {
                        //请将手指放入指夹
                        gluCallback.deviceState(GLU_STATE_3);
                        gluCallback.deviceState("环境温湿度正常或者等了10秒了,可以插入手指");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_HJER) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("检测前环境温度不符测试条件");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_HJER_ETL) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("环境温度偏低");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_HJER_ETH) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("环境温度偏高");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_HJER_EHH) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("环境湿度偏高");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_HJER_EHL) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("环境湿度偏低");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_DEVICE) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("设备故障,请联系维修");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_SZER_TL) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("手指温度偏低");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_SZER_TH) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("手指温度偏高");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_HJER) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("检测前环境温度不符测试条件");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_FINGERIN) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("手指已经放入");
                    }
                }
                if (event.getType() == GlumeterEventType.PRC_BEGIN) {
                    if (gluCallback != null) {
                        gluCallback.deviceState(GLU_STATE_4);
                        gluCallback.deviceState("测量开始了");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_FNGR) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("未检测到手指");
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_ERRO) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("手指已拔出");
                    }
                }
                if (event.getType() == GlumeterEventType.PRC_PROCESS) {
                    if (gluCallback != null) {
                        //10 - 100（10）
                        try {
                            int processValue = Integer.parseInt(event.getContent().toString());
                            gluCallback.detectProgress(processValue);

                            if (processValue == 100) {
                                gluCallback.deviceState(GLU_STATE_5);
                            }
                        } catch (Exception e) {

                        }
                        gluCallback.deviceState("测试中 》》" + event.getContent());
                    }
                }
                if (event.getType() == GlumeterEventType.PRC_INITDATAFINISH) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("检测完成");
                        //接收测试结果
                        W_GluResult result = (W_GluResult) event.getContent();
                        GluResultEntity gluResultEntity = new GluResultEntity(result);
                        gluCallback.resultReceived(gluResultEntity);
                        //检测完成设置指尖血
                    }
                }
                if (event.getType() == GlumeterEventType.PRC_UPDATESTART) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("程序升级开始");
                    }
                }
                if (event.getType() == GlumeterEventType.PRC_UPDATE) {
                    if (gluCallback != null) {
                        long time = (long) event.getContent();
                        gluCallback.deviceState("程序升级完成，发送数据成功,用时=" + time);
                    }
                }
                if (event.getType() == GlumeterEventType.PRC_UPDATE_PRO) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("程序升级" + event.getContent());
                    }
                }
                if (event.getType() == GlumeterEventType.ERR_UPDATE) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("程序升级失败" + GlumeterEventType.ERR_UPDATE.getName());
                    }
                }
                if (event.getType() == GlumeterEventType.PRC_BLUETOOTH_UPDATE_START) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("蓝牙开始升级");
                    }
                }
                if (event.getType() == GlumeterEventType.PRC_BLUETOOTH_UPDATE_PRO) {
                    if (gluCallback != null) {
                        ProgressBean bean = (ProgressBean) event.getContent();
                        gluCallback.deviceState("蓝牙升级进度=" + bean.getPercent() + "\nspeed=" + bean.getSpeed() + "avgSpeed=" + bean.getAvgSpeed());
                    }
                }
                if (event.getType() == GlumeterEventType.PRC_BLUETOOTH_UPDATE_FAIL) {
                    if (gluCallback != null) {
                        gluCallback.deviceState("蓝牙升级失败");
                    }
                    if (event.getType() == GlumeterEventType.PRC_BLUETOOTH_UPDATE_FINISH) {
                        if (gluCallback != null) {
                            gluCallback.deviceState("蓝牙升级完成");
                        }
                    }
                    if (event.getType() == GlumeterEventType.PRC_BLUETOOTH_UPDATE_ERROR) {
                        if (gluCallback != null) {
                            gluCallback.deviceState("蓝牙升级错误=" + event.getContent());
                        }
                    }
                    if (event.getType() == GlumeterEventType.PRC_BLUETOOTH_UPDATE_STOP) {
                        if (gluCallback != null) {
                            gluCallback.deviceState("蓝牙升级停止");
                        }
                    }//G
                    if (event.getType() == GlumeterEventType.PRC_CANUPDATE) {
                        if (gluCallback != null) {
                            gluCallback.deviceState("血糖仪有可升级文件程序");
                        }
                    }
                    if (event.getType() == GlumeterEventType.PRC_TESTING) {
                        if (gluCallback != null) {
                            gluCallback.deviceState("正在检测中，请勿升级");
                        }
                    }
                }
            }
        }
    }

    private W_GlumeterListener listener = new W_GlumeterListener() {
        @Override
        public void onEvent(W_GlumeterEvent event) {
            Message message = new Message();
            message.what = 60;
            message.obj = event;
            if (mHandler != null) {
                mHandler.sendMessage(message);
            }
        }

        @Override
        public void onEvent(GlumeterEvent event) {
            Message message = new Message();
            message.what = 61;
            message.obj = event;
            if (mHandler != null) {
                mHandler.sendMessage(message);
            }
        }
    };

    private void conn(BleRssiDevice bleRssiDevice) {
        if (bleRssiDevice != null && glumeterWorker != null) {
            glumeterWorker.connDevice(bleRssiDevice);
        }
    }

}
